package com.bosc.automationui.service;

import com.bosc.automationui.repository.ETLJoblDependencyRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.bosc.automationui.entity.ETLJobDependency;

import java.util.*;
import java.util.concurrent.ArrayBlockingQueue;

@Service
public class ETLDependencyService {
    @Autowired
    ETLJoblDependencyRepository etlJoblDependencyRepository;

    public HashMap<String, Object> getDependencyRecords() {
        HashMap<String, Object> result = new HashMap<>();
        Iterable<ETLJobDependency> dependencyList = etlJoblDependencyRepository.findAll();
        result.put("code", "0");
        result.put("msg", "success");
        result.put("data", dependencyList);
        return result;
    }

    public HashMap<String, Object> searchDependencyChain(String predicate) {
        HashMap<String, Object> result = new HashMap<>();
        List<ETLJobDependency> resultList = etlJoblDependencyRepository.findByEtlJob(predicate);

//        List<List<ETLJobDependency>> testList = new ArrayList<>();

        System.out.println("Got the point");
        for (ETLJobDependency e : resultList) {
            System.out.println(e.getEtlJob() + " , "+e.getDependencyJob());
        }

        ArrayDeque<ETLJobDependency> dependencyQ = new ArrayDeque<>(resultList);
        while (dependencyQ.size() > 0) {
            ETLJobDependency dependency  = dependencyQ.removeFirst();
            List<ETLJobDependency> subDeps = etlJoblDependencyRepository.findByEtlJob(dependency.getDependencyJob());

//            testList.add(subDeps);

            if (!dependency.getDependencyJob().equals(dependency.getEtlJob()) && subDeps.size() != 0) {
                dependencyQ.addAll(subDeps);
                resultList.addAll(subDeps);
            }
        }
//        result.put("test",testList);
        result.put("code", "0");
        result.put("msg", "success");
        result.put("data", resultList);
        return result;
    }
}
